<template>
    <div>
        <van-nav-bar
            title="群聊设置"
            left-text="返回"
            left-arrow
            @click-left="$router.go(-1)"/>
        <van-cell-group inset>
            <van-cell :title="groupName" size="large">
                <template #icon>
                    <van-image width="40" height="40" center :src="groupAvatar" />
                </template>
            </van-cell>
            <van-cell title="群主" :value="ownerNickname" />
        </van-cell-group>
        
        <van-cell-group inset>
            <van-cell title="群聊成员" :value="`${memberCount}人`" is-link @click="showMembersDialog = true" />
            <van-cell title="邀请好友" is-link @click="onInviteMembers" />
            <van-cell title="群聊公告" is-link @click="showAnnouncementDialog = true">
                <template #right-icon>
                    <van-badge dot v-if="hasNewAnnouncement" color="#07C160" />
                    <van-icon name="arrow" />
                </template>
            </van-cell>
            <van-cell title="修改群名称" is-link v-if="isOwner" @click="showRenameDialog = true" />
            <van-cell title="退出群聊" is-link @click="showQuitGroupDialog = true" />
            <van-cell title="解散群聊" is-link v-if="isOwner" @click="showDismissGroupDialog = true" />
        </van-cell-group>

        <!-- 群成员列表弹窗 -->
        <van-action-sheet v-model="showMembersDialog" title="群聊成员">
            <div class="member-list">
                <van-grid :border="false" :column-num="5">
                    <van-grid-item v-for="member in sortedMembers" :key="member._id">
                        <div class="member-container">
                            <van-image width="50" height="50" :src="member.headImgUrl" />
                            <div class="member-name">{{ member.nickname }}</div>
                            <div class="member-tag" v-if="isGroupOwner(member._id)">群主</div>
                        </div>
                    </van-grid-item>
                    <van-grid-item v-if="!isFullGroup">
                        <div class="member-container" @click="onInviteMembers">
                            <van-icon name="add-o" size="50" />
                            <div class="member-name">邀请</div>
                        </div>
                    </van-grid-item>
                </van-grid>
            </div>
        </van-action-sheet>

        <!-- 群公告弹窗 -->
        <van-dialog
            v-model="showAnnouncementDialog"
            title="群公告"
            show-cancel-button
            :confirm-button-text="isOwner ? '保存' : '确定'"
            :show-confirm-button="isOwner"
            @confirm="updateAnnouncement"
            @open="markAnnouncementAsRead"
        >
            <van-field
                v-model="announcementText"
                type="textarea"
                rows="4"
                :readonly="!isOwner"
                placeholder="请输入群公告"
                :maxlength="200"
                show-word-limit
            />
            <div v-if="announcementText && !isOwner" class="announcement-info">
                <div class="announcement-updater">{{ lastAnnouncementUpdater }}</div>
                <div class="announcement-time">{{ lastAnnouncementTime }}</div>
            </div>
        </van-dialog>

        <!-- 修改群名称弹窗 -->
        <van-dialog
            v-model="showRenameDialog"
            title="修改群名称"
            show-cancel-button
            @confirm="renameGroup"
        >
            <van-field
                v-model="newGroupName"
                placeholder="请输入群名称"
                :maxlength="20"
                show-word-limit
            />
        </van-dialog>

        <!-- 退出群聊确认弹窗 -->
        <van-dialog
            v-model="showQuitGroupDialog"
            title="退出群聊"
            show-cancel-button
            @confirm="quitGroup"
        >
            <div class="quit-dialog-content">
                <p>确定退出群聊"{{ groupName }}"吗？</p>
                <p class="quit-warning">退出后，将不再接收此群聊消息</p>
            </div>
        </van-dialog>

        <!-- 解散群聊确认弹窗 -->
        <van-dialog
            v-model="showDismissGroupDialog"
            title="解散群聊"
            show-cancel-button
            @confirm="dismissGroup"
        >
            <div class="quit-dialog-content">
                <p>确定解散群聊"{{ groupName }}"吗？</p>
                <p class="quit-warning">解散后，所有成员将被移出群聊，且无法恢复</p>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import socket from '@/socket';

export default {
    name: "GroupMoreOperateView",
    data() {
        return {
            groupInfo: null,
            showMembersDialog: false,
            showAnnouncementDialog: false,
            showRenameDialog: false,
            showQuitGroupDialog: false,
            showDismissGroupDialog: false,
            announcementText: '',
            newGroupName: '',
            members: [],
            hasNewAnnouncement: false,
            lastAnnouncementUpdater: '群主',
            lastAnnouncementTime: ''
        }
    },
    computed: {
        ...mapState(['user', 'groupChatList']),
        groupId() {
            return this.$route.query.groupChat_id;
        },
        groupName() {
            return this.groupInfo?.groupName || '';
        },
        groupAvatar() {
            return this.groupInfo?.groupAvatar || 'https://img.yzcdn.cn/vant/cat.jpeg';
        },
        memberCount() {
            return this.members.length;
        },
        isOwner() {            
            return this.groupInfo?.owner?._id?.toString() === this.user._id.toString();        
        },
        isFullGroup() {
            return this.members.length >= (this.groupInfo?.maxMembers || 500);
        },
        ownerNickname() {            
            // 直接从owner对象获取昵称            
            return this.groupInfo?.owner?.nickname || '未知';        
        },
        sortedMembers() {
            // 将群主排在首位，其他成员按原顺序排列
            if (!this.members.length) return [];
            
            return [...this.members].sort((a, b) => {
                if (this.isGroupOwner(a._id)) return -1;
                if (this.isGroupOwner(b._id)) return 1;
                return 0;
            });
        }
    },
    mounted() {
        this.fetchGroupInfo();
        this.setupAnnouncementListener();
    },
    beforeDestroy() {
        // 移除监听器
        socket.off('groupAnnouncementUpdated');
    },
    methods: {
        ...mapMutations(['upGroupChats']),
        fetchGroupInfo() {
            // 从store中获取群聊信息
            this.groupInfo = this.groupChatList.find(item => item._id === this.groupId);
            
            if (this.groupInfo) {
                this.newGroupName = this.groupInfo.groupName;
                this.announcementText = this.groupInfo.announcement || '';
                
                
                
                // 获取群成员信息
                socket.emit('get_group_members', {
                    groupId: this.groupId
                }, (response) => {
                    if (response && response.code === 200) {
                        this.members = response.members || [];
                        
                        // 检查本地存储，判断是否有未读公告
                        const lastReadTime = localStorage.getItem(`announcement_read_${this.groupId}`);
                        const lastUpdateTime = localStorage.getItem(`announcement_update_${this.groupId}`);
                        
                        if (lastUpdateTime && (!lastReadTime || lastReadTime < lastUpdateTime)) {
                            this.hasNewAnnouncement = true;
                        }
                    } else {
                        this.$toast.fail('获取群成员失败');
                    }
                });
            } else {
                this.$toast.fail('获取群聊信息失败');
                this.$router.go(-1);
            }
        },
        
        isGroupOwner(memberId) {            return this.groupInfo?.owner?._id?.toString() === memberId.toString();        },
        
        setupAnnouncementListener() {
            // 监听群公告更新
            socket.on('groupAnnouncementUpdated', (data) => {
                if (data.groupId === this.groupId) {
                    // 更新本地群聊信息
                    const index = this.groupChatList.findIndex(item => item._id === this.groupId);
                    if (index !== -1) {
                        this.$set(this.groupChatList[index], 'announcement', data.announcement);
                        
                        // 如果当前不是在查看公告，设置未读标记
                        if (!this.showAnnouncementDialog) {
                            this.hasNewAnnouncement = true;
                            
                            // 保存更新时间到本地存储
                            localStorage.setItem(`announcement_update_${this.groupId}`, Date.now());
                            
                            // 查找更新者昵称
                            const updater = this.members.find(member => member._id.toString() === data.updatedBy.toString());
                            if (updater) {
                                this.$toast(`${updater.nickname}更新了群公告`);
                            } else {
                                this.$toast('群公告已更新');
                            }
                        }
                        
                        // 更新公告文本
                        this.announcementText = data.announcement;
                    }
                }
            });
        },
        
        markAnnouncementAsRead() {
            // 标记公告为已读
            this.hasNewAnnouncement = false;
            // 保存阅读时间到本地存储
            localStorage.setItem(`announcement_read_${this.groupId}`, Date.now());
        },
        
        onInviteMembers() {
            // 跳转到邀请好友页面
            this.$router.push({
                path: '/invite-group-members',
                query: { groupChat_id: this.groupId }
            });
        },
        
        updateAnnouncement() {
            if (!this.isOwner) return;
            
            socket.emit('update_group_announcement', {
                groupId: this.groupId,
                userId: this.user._id,
                announcement: this.announcementText
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('更新群公告成功');
                    
                    // 更新本地群聊信息
                    const index = this.groupChatList.findIndex(item => item._id === this.groupId);
                    if (index !== -1) {
                        this.$set(this.groupChatList[index], 'announcement', this.announcementText);
                        
                        // 保存更新时间到本地存储
                        localStorage.setItem(`announcement_update_${this.groupId}`, Date.now());
                    }
                } else {
                    this.$toast.fail(response?.message || '更新群公告失败');
                }
            });
        },
        
        renameGroup() {
            if (!this.isOwner) return;
            
            socket.emit('rename_group', {
                groupId: this.groupId,
                userId: this.user._id,
                newName: this.newGroupName
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('修改群名称成功');
                    
                    // 更新本地群聊信息
                    const index = this.groupChatList.findIndex(item => item._id === this.groupId);
                    if (index !== -1) {
                        this.$set(this.groupChatList[index], 'groupName', this.newGroupName);
                    }
                } else {
                    this.$toast.fail(response?.message || '修改群名称失败');
                }
            });
        },
        
        quitGroup() {
            socket.emit('quit_group', {
                groupId: this.groupId,
                userId: this.user._id
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('退出群聊成功');
                    
                    // 移除本地群聊
                    const newGroupList = this.groupChatList.filter(item => item._id !== this.groupId);
                    this.upGroupChats(newGroupList);
                    
                    // 返回到消息页面
                    this.$router.push('/message');
                } else {
                    this.$toast.fail(response?.message || '退出群聊失败');
                }
            });
        },
        
        dismissGroup() {
            if (!this.isOwner) return;
            
            socket.emit('dismiss_group', {
                groupId: this.groupId,
                userId: this.user._id
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('解散群聊成功');
                    
                    // 移除本地群聊
                    const newGroupList = this.groupChatList.filter(item => item._id !== this.groupId);
                    this.upGroupChats(newGroupList);
                    
                    // 返回到消息页面
                    this.$router.push('/message');
                } else {
                    this.$toast.fail(response?.message || '解散群聊失败');
                }
            });
        }
    }
}
</script>

<style lang="less" scoped>
.van-cell-group {
    margin-top: 10px;
}

.member-list {
    max-height: 60vh;
    overflow-y: auto;
    padding: 10px 0;
}

.member-container {
    position: relative;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.member-name {
    font-size: 12px;
    color: #333;
    margin-top: 5px;
    width: 100%;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.member-tag {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 10px;
    background-color: #07C160;
    color: #fff;
    padding: 2px 4px;
    border-radius: 10px;
}

.quit-dialog-content {
    padding: 10px 20px;
    text-align: center;
    
    .quit-warning {
        color: #ff4d4f;
        font-size: 14px;
        margin-top: 5px;
    }
}

.announcement-info {
    padding: 10px 16px;
    font-size: 12px;
    color: #999;
    text-align: right;
    
    .announcement-updater {
        margin-bottom: 4px;
    }
}
</style>